//
//  HomeViewController.m
//  ActiveDeck
//
//  Created by BigChicken on 1/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "PresentationInfoViewController.h"
#import "AboutViewController.h"
#import "LoginViewController.h"
#import "HttpRequest.h"
#import "AD_PresentationInfo.h"
#import <QuartzCore/QuartzCore.h>
#import "AvailablePID.h"
#import "Init.h"
#import "CustomMovieViewController.h"
#import "Reachability.h"

BOOL LOGIN = false;
BOOL useLog = false;
int LogIndex;
int versionNo;
AvailablePID *PIDupdater;


@implementation HomeViewController

#define ACTIVEDECKPASS @"ActiveDeckPass"
#define ACTIVEDECKUSER @"ActiveDeckUser"
#define ACTIVEDECKPID @"ActiveDeckPID"
#define ACTIVEDECKHISTORYPIDS @"AcetiveDeckIDS"



@synthesize greeting, initOB , presentID, progressBar, approval;
@synthesize AuthNode, loginXML, loginVC, Bt_Logout, Bt_Go,Bt_Cancel, presentName;
@synthesize Lab_PresentName, ImgV_Icon, Bt_ShowVersion, Arr_PID, Lb_PID;
@synthesize PIDTableCell,PIDTable,avaibleTimer, ErrorLogText,loadingView,IUV_DarkOverlay,cont_Username, Bt_About, cmvc, TABLEHIDE, blockedView, Bt_CancelBlocked, Username_Label, loggedInBar, environment, hasInternet;


#pragma mark -
#pragma mark Timer for Passing Avalible List

- (void)BonjourCheck 
{
    if(!TABLEHIDE)
    {
        [PIDupdater updateList];
        
        Arr_PID = [PIDupdater.List_PID copy];
        
        if([Arr_PID count] > 0)
            [PIDTable reloadData];
        
        [PIDupdater start];
    } 
}

-(void)updatePIDList
{
    TABLEHIDE = FALSE;
}



#pragma mark -
#pragma mark Start Checking all avaliable PID
//#define Locked 0
//#define History 1
//#define Anonymous 2



//-(void)updateHistoryPID:(NSString *)newEnterPID
//{
//    AD_PresentationInfo *newPID= [[AD_PresentationInfo alloc] GetPresentADInfo:newEnterPID];
//    
//    newPID.pStatus = 1;
//    
//    NSLog(@"Pstatus = %d, PID=%d , Pstatus=%@ , pIcon=%@ ", newPID.pStatus, newPID.presentationID, [newPID pName], [newPID iconAddress] );
//    
//    
//    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//    NSData *dataRepresentingSavedArray = [prefs objectForKey:ACTIVEDECKHISTORYPIDS];
//    NSMutableArray *historyPID = [[NSMutableArray alloc] init];
//    
//    if (dataRepresentingSavedArray != nil)
//    {
//        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
//        
//        if (oldSavedArray != nil)
//            historyPID = [[NSMutableArray alloc] initWithArray:oldSavedArray];
//        
//    }
//    
//    
//    for (AD_PresentationInfo *adOld in historyPID)
//    {
//        if (adOld.presentationID  == newPID.presentationID)
//        {
//            [historyPID removeObject:adOld];
//            break;
//        }
//    }
//    
//    [historyPID insertObject:newPID atIndex:0];
//    
//    
//    if([historyPID count] > 5)
//        [historyPID removeObjectAtIndex:5];
//    
//    NSLog(@"Save historyCount=%d",[historyPID count]);
//    
//    [prefs setObject:[NSKeyedArchiver archivedDataWithRootObject:historyPID] forKey:ACTIVEDECKHISTORYPIDS];
//    [prefs synchronize];
//    
//    [newPID release];
//}



#pragma mark -
#pragma mark Display Available Presentation ID within table

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    UILabel *Lab_PID = (UILabel *)[cell viewWithTag:1];
    NSLog(@"Cell PID:%@", Lab_PID.text);
    
    TABLEHIDE = TRUE;
    //    AD_PresentationInfo *pInfo = [Arr_PID objectAtIndex:indexPath.row];
    AD_PresentationInfo *pInfo = [PIDupdater GetPresInfoObject:Lab_PID.text];
    if(pInfo){
        presentID.text = [NSString stringWithFormat:@"%d", pInfo.presentationID];
        [self DownloadPresentation];
    } else {
        NSLog(@"Presentation Info not found for %@", Lab_PID.text);
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    return [Arr_PID count];
}




// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    
    if(cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"availableCell" owner:self options:NULL];
        cell = PIDTableCell;
    }
    
    AD_PresentationInfo *pInfo = [Arr_PID objectAtIndex:indexPath.row];
    UILabel *Lab_PID = (UILabel *)[cell viewWithTag:1];
    UILabel *Lab_PName = (UILabel *)[cell viewWithTag:2];
    UIImageView *Img_Icon = (UIImageView *)[cell viewWithTag:3];
    UIImageView *Img_Lock = (UIImageView *)[cell viewWithTag:4];
    
    Lab_PID.text = [NSString stringWithFormat: @"%d",pInfo.presentationID];
    Lab_PName.text = pInfo.pName;
    
    NSURL *URL_Icon = [NSURL URLWithString:[NSString stringWithFormat:@"%@/Config.svc/Logo/%d", [HttpRequest GetSvcURL],pInfo.presentationID]];
    
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:URL_Icon cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    
    NSData *dataIcon = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
    
    //NSData *dataIcon = [[NSData alloc] initWithContentsOfURL:URL_Icon];
    Img_Icon.image = [UIImage imageWithData:dataIcon];
    
    if (pInfo.pStatus < 1)
        Img_Lock.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_lock" ofType:@"png"]];
    else if(pInfo.pStatus < 2)
        Img_Lock.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_history" ofType:@"png"]];
    else
        Img_Lock.hidden = TRUE;
    
    //[dataIcon release];
    [req release];
    
    return cell;
}


#pragma mark -
#pragma mark Check Network Avaliblity 

//- (void) checkNetworkStatus:(NSNotification *)notice
//{
//    // called after network status changes
//    
//    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
//    switch (internetStatus)
//    
//    {
//        case NotReachable:
//        {
//            NSLog(@"The internet is down.");
//            self.internetActive = NO;
//            
//            break;
//            
//        }
//        case ReachableViaWiFi:
//        {
//            NSLog(@"The internet is working via WIFI.");
//            self.internetActive = YES;
//            
//            break;
//            
//        }
//        case ReachableViaWWAN:
//        {
//            NSLog(@"The internet is working via WWAN.");
//            self.internetActive = YES;
//            
//            break;
//            
//        }
//    }
//
//}

#pragma mark -
#pragma mark Showing ActiveDeck Version


-(IBAction) showVersion
{
    if(versionNo < 1)
    {
        versionNo++;
        
        [Bt_ShowVersion setTitle:[NSString stringWithFormat: @"Version %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] forState:UIControlStateNormal];
    }
    else
    {
        versionNo--;
        [Bt_ShowVersion setTitle:[NSString stringWithFormat: @"Build %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]] forState:UIControlStateNormal];
    }
}

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}

#pragma mark -
#pragma mark About Button
-(IBAction)showAbout:(id)sender{
    [self readyMoviePlayer];
}

-(void)readyMoviePlayer{
    cmvc = [[CustomMovieViewController alloc] init];
    
    [cmvc set_cmvcDelegate:self];
    
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"About_Button_Video" ofType:@"m4v"];
    
    [cmvc readyPlayer:moviePath :CGRectMake(134, 700, 480, 270) :@"Portrait" :YES :NO];
    
    
    [[self view] addSubview:cmvc];
}

-(void)rotateForMovie:(BOOL)shouldRotate{
    [_delegate rotateForMovie:shouldRotate];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField isEqual:presentID]) {
        if(cmvc != nil){ 
            if(![cmvc isStopped]){
                [[cmvc mp] stop];
            }
        }
    }
}

#pragma mark -
#pragma mark Logging

-(IBAction) userLogout
{
    NSLog(@"Show Login Window");
    loginVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    loginVC.loginSuccess = FALSE;
    Bt_Logout.hidden = TRUE;
    Username_Label.hidden = YES;
    loggedInBar.hidden = YES;
    
    //NSMutableString *emptyString = [[NSMutableString alloc] initWithString:@""];
    NSString *emptyString = [NSString stringWithString:@""];
    
    loginVC.Txt_Email.text = emptyString;
    loginVC.Txt_Pass.text = emptyString;
    
    [environment clearEnvironment];
    
    NSLog(@"User Logged Out: removed from preferences");
}

#pragma mark -
#pragma mark Redirect the Log and Scan for error

- (void)redirectConsoleLogToDocumentFolder
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *LogDirectory = [documentsDirectory
                              stringByAppendingPathComponent:@"Log"];
    
	NSFileManager *nsFM = [NSFileManager defaultManager];
	BOOL isDir = YES;
    
	if(![nsFM fileExistsAtPath:LogDirectory isDirectory:&isDir])
		[nsFM createDirectoryAtPath:LogDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *logPath;
    NSDate *latestDate;
    
    for (int i =1 ; i < 8 ; i++)
    {
        logPath = [NSString stringWithFormat:@"%@/%@%d.log", LogDirectory, @"console", i];
        LogIndex = i;
        
        if(![nsFM fileExistsAtPath:logPath])
            break;
        else 
        {
            NSDictionary *fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:logPath error:nil];
            NSDate *thisFileDate = [fileAttribs objectForKey:NSFileModificationDate];
            
            
            if(i==1)
                latestDate = thisFileDate;
            else if([thisFileDate compare:latestDate] == NSOrderedAscending)
            {
                [nsFM removeItemAtPath:logPath error:nil];
                break;
            }
            else if(i == 7)
            {
                LogIndex = 1;
                logPath = [NSString stringWithFormat:@"%@/%@%d.log", LogDirectory, @"console", 1];
                [nsFM removeItemAtPath:logPath error:nil];
            }
        }
    }
	freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"w+",stderr);
}

- (void)ScanLogForError
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
    
	NSString *logPath;
    //LogIndex = 4;
    int lIndex = LogIndex -1;
    if(lIndex < 1)
        lIndex = 7;
    
    logPath = [NSString stringWithFormat:@"%@/Log/%@%d.log", documentsDirectory, @"console", lIndex];
    
    NSLog(@"LogPath:%@", logPath);
    
    NSString *logText = [NSString stringWithFormat:@"<![CDATA[%@]]>", [NSString stringWithContentsOfFile:logPath encoding:NSASCIIStringEncoding error:nil]];
    
    NSMutableArray *listOfKeyWords = [[NSMutableArray alloc] init];
    [listOfKeyWords addObject:@"memory"];
    [listOfKeyWords addObject:@"exception"];
    [listOfKeyWords addObject:@"SIGABT"];
    [listOfKeyWords addObject:@"violation"];
    [listOfKeyWords addObject:@"Terminating"];
    
    
    for (NSString *searchFor in listOfKeyWords)
    {
        NSRange range = [logText rangeOfString:searchFor];
        
        if (range.location != NSNotFound)
        {
            ErrorLogText = [[NSString alloc] initWithString:logText];
            
            NSString *lineBreak = [[NSString alloc] initWithString:@"ActiveDeck may not have exited cleanly last time.\nWould you like to submit an error report to help prevent this in the future?"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:lineBreak delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
            [alert show];
            [alert release];
            [lineBreak release];
            break;
            
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            [prefs removeObjectForKey:@"KIOSK"];
            [prefs synchronize];
        }
    }
    [listOfKeyWords release];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 1)
    {
        NSLog(@"Submitting Error message to webservice");
        [self postErrorToWeb];
    }
    //else if (buttonIndex == 1)
    //{
    //    [self showInfo:self];
    //}
    else
    {
        NSLog(@"cancel");
    }
}

-(void)postErrorToWeb
{
    //NSLog(@"Version:%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]);
    //NSLog(@"UDID:%@",  [[UIDevice currentDevice]uniqueIdentifier]);
    // NSLog(@"Gan:%@", GanError);
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    if(ErrorLogText == NULL)
        ErrorLogText = [NSString stringWithFormat:@"%@", @"Error log become NULL again"];
    
    NSString *UDID = [[UIDevice currentDevice] uniqueIdentifier];
    NSString *ShortVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *LongVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    NSString *PresentationIDInfo = [prefs stringForKey:ACTIVEDECKPID];
    NSLog(@"UDID = %@ \n SV = %@ \n LV = %@ \n PINFO = %@\n", UDID, ShortVersion, LongVersion, PresentationIDInfo);
    
    NSString *errorReport = [NSString stringWithFormat:@"<ErrorReport Source=\"App\" Version=\"%@(%@)\" Presentation=\"%@\" UDID=\"%@\" >%@</ErrorReport>",
                             [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                             [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"],
                             [prefs stringForKey:ACTIVEDECKPID],
                             [[UIDevice currentDevice] uniqueIdentifier],
                             ErrorLogText];
    
    //NSLog(@"ErrorReport:%@", errorReport);
    
    
    NSString *errorReportURL = [NSString stringWithFormat:@"%@/Config.svc/SubmitErrorReport", [HttpRequest GetSvcURL]];
    
    HttpRequest *postError = [[HttpRequest alloc] autorelease];
    [postError XML_PostRequest:errorReport urlString:errorReportURL];
    NSLog(@"Error report submitted.");
    [ErrorLogText release];
}


#pragma mark -
#pragma mark Get Auto Update Info

- (NSString*)FetchPInfo:(int)PID
{
    NSError *loadError;
    
    NSString *URLInfo = [NSString stringWithFormat:@"%@/%@/%d",[HttpRequest GetSvcURL], @"Config.svc/GetPresentationInfo", PID];
    
    NSString *URLContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:URLInfo] encoding:NSUTF8StringEncoding error:&loadError];
    
    return URLContent;
}

- (BOOL)AutoUpdateCheck
{
    NSString *URLContent = [self FetchPInfo:initOB.PID];
    NSString *pInfo = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>%@",URLContent];
    
    NSDictionary *namespaces = [NSDictionary dictionaryWithObjectsAndKeys:
								@"http://www.activedeck.com/PowerPoint/", @"ad",
								nil];
    
    NSData *xmlData = [pInfo dataUsingEncoding:NSUTF8StringEncoding];
    
    GDataXMLDocument *pInfoDoc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
    GDataXMLElement *pName = [[pInfoDoc nodesForXPath:@"//ad:Presentation" namespaces:namespaces error:nil] objectAtIndex:0];
    int latestVersion = [[[pName attributeForName:@"Version"]stringValue]intValue];
    
    [pInfoDoc release];
    if(latestVersion != initOB.iVersion)
        return TRUE;
    else
        return FALSE;
}

#pragma mark -
#pragma mark Check Presentation Information

- (void)GetPresentInfo:(int)PID
{
    [Bt_About setEnabled:NO];
    [Bt_Logout setEnabled:NO];
    if(cmvc != nil){ 
        if(![cmvc isStopped]){
            [[cmvc mp] stop];
        }
    }
    
    NSString *URLContent = [self FetchPInfo:PID];
    
    if(URLContent == NULL )
    {  
//        UIAlertView *alertMSG = [UIAlertView alloc];
//        alertMSG = [alertMSG initWithTitle:@"Internet Connection Failure"
//								   message:@"Please check your Internet connection and try again."
//								  delegate:self 
//						 cancelButtonTitle:@"OK" 
//						 otherButtonTitles:nil];
//		
//		[alertMSG show];
//        [alertMSG release];
        
        hasInternet = NO;
		
    } else {
        hasInternet = YES;
    }
    
    if(hasInternet){
        NSString *pInfo = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>%@",URLContent];
        
        
        NSString *searchFor = @"Invalid Presentation ID";
        NSRange range;
        range = [pInfo rangeOfString:searchFor];
        
        if (range.location != NSNotFound)
        {
            UIAlertView *alertMSG = [UIAlertView alloc];
            alertMSG = [alertMSG initWithTitle:@"Incorrect ID"
                                       message:@"Please Enter Correct Presentation ID"
                                      delegate:self 
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles:nil];
            
            [alertMSG show];
            [alertMSG release];
            
            return;
        }
        
        NSURL *URL_Icon = [NSURL URLWithString:[NSString stringWithFormat:@"%@/Config.svc/Logo/%@",[HttpRequest GetSvcURL],presentID.text]];
        NSData *dataIcon = [[NSData alloc] initWithContentsOfURL:URL_Icon];
        ImgV_Icon.image = [UIImage imageWithData:dataIcon];
        [dataIcon release];
        
        NSDictionary *namespaces = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"http://www.activedeck.com/PowerPoint/", @"ad",
                                    nil];
        
        NSData *xmlData = [pInfo dataUsingEncoding:NSUTF8StringEncoding];
        
        GDataXMLDocument *pInfoDoc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
        GDataXMLElement *pName = [[pInfoDoc nodesForXPath:@"//ad:Presentation" namespaces:namespaces error:nil] objectAtIndex:0];
        GDataXMLElement *accessNode = [[pInfoDoc nodesForXPath:@"//ad:Presentation/ad:UserAccess" namespaces:namespaces error:nil] objectAtIndex:0];
        
        Lab_PresentName.text = [NSString stringWithString:[[pName attributeForName:@"Name"] stringValue]];
        NSString *userAccess = [[accessNode attributeForName:@"Value"]stringValue];
        
        
        if([userAccess isEqualToString:@"Anonymous"])
        {        
            [self BuildAnonymousXMLAuth];
            [self DownloadPresentationInBackground];
        }
        else
        {
            
            if (environment.hasLogin) {
                loginXML = environment.getAuthentication;
                AuthNode = environment.authNode;
                loginVC.cont_UserName = environment.username;
                loginVC.loginSuccess = YES;
            }
            
            if(!loginVC.loginSuccess)
            {
                useLog = TRUE;
                NSLog(@"Show Login Window");
                loginVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                
                [Bt_Logout setEnabled:FALSE];
                [self presentModalViewController:loginVC animated:YES];
            }
            else
                [self DownloadPresentationInBackground];
        }
        
        [pInfoDoc release];
    } else {
        [self DownloadPresentationInBackground];
    }
}

#pragma mark -
#pragma mark Build Authentication XML structure

-(void)BuildAnonymousXMLAuth
{
    GDataXMLElement *Authentication = [GDataXMLNode elementWithName:@"Authentication"];
    GDataXMLNode *UserName = [GDataXMLNode attributeWithName:@"UserName" stringValue:@""];
    GDataXMLNode *Password = [GDataXMLNode attributeWithName:@"Password" stringValue:@""];
    
    [Authentication addChild:UserName];
    [Authentication addChild:Password];     
    
    GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithRootElement:Authentication];
    NSData	*xData = document.XMLData;
    loginXML = [[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding];
    
    AuthNode = [[GDataXMLElement alloc]init];
    AuthNode = [Authentication copy];
    
    [document release];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [self hideAll:TRUE];
    
    if(loginVC.loginSuccess & useLog)
    {
        useLog = FALSE;
        Bt_Logout.hidden = FALSE;
        Username_Label.hidden = FALSE;
        Username_Label.text = environment.simpleUsername;
        loginXML = environment.getAuthentication;
        AuthNode = environment.authNode;
        if([presentID.text length] > 5)
            [self DownloadPresentationInBackground];
    }
}


#pragma mark -
#pragma mark Download and Process the Presentation


-(IBAction)cancelDownload
{
    PIDTable.hidden = FALSE;
    initOB.cancel = TRUE;
    Bt_About.enabled = TRUE;
    Bt_Logout.enabled = TRUE;
    [self hideAll:TRUE];
}

-(void)hideAll:(BOOL)shouldHide{
    IUV_DarkOverlay.hidden = shouldHide;
    loadingView.hidden = shouldHide;
    Bt_Go.enabled = shouldHide;
    progressBar.progress = (int)!shouldHide;
    greeting.text = @"Your presentation is loading...";
}

-(void)viewWillAppear:(BOOL)animated
{
    PIDTable.hidden = FALSE;
    blockedView = [[[NSBundle mainBundle] loadNibNamed:@"BlockedUserView" owner:self options:nil] objectAtIndex:0];
    
    [blockedView setHidden:YES];
    [self.view addSubview:blockedView];
}

- (IBAction)DownloadPresentation
{
    if([presentID.text length] < 6 || [presentID.text length] > 6)
    {
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"Incorrect ID"
								   message:@"Please Enter Correct Presentation ID"
								  delegate:self 
						 cancelButtonTitle:@"OK" 
						 otherButtonTitles:nil];
		
		[alertMSG show];
        [alertMSG release];
    }
    else
        [self GetPresentInfo:[presentID.text intValue]] ;
    
}

- (void)DownloadPresentationInBackground
{
    if(!loginVC.loginSuccess)
        cont_Username = [[NSString alloc] initWithFormat:@"Anonymous"];
    else
        cont_Username = environment.username;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:presentID.text forKey:ACTIVEDECKPID];
    [prefs synchronize];
    
    [PIDupdater updateHistoryPID:presentID.text];
    //    [self updateHistoryPID:presentID.text];
    
    [presentID resignFirstResponder];
    
    Lb_PID.text = presentID.text;
    [self hideAll:FALSE];
    
	
    initOB = [Init alloc];
    
    [self performSelectorInBackground:@selector(InitializeOB:) withObject:presentID.text];
}

- (void)InitializeOB:(NSString*)PID
{  
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	[initOB setDelegate:self];
    
	BOOL initializedConfig = [initOB InitialConfig:[PID intValue] Authentication:loginXML HasInternet:hasInternet];	
    
    if(!initializedConfig){
        [self hideAll:TRUE];
        //[presentID becomeFirstResponder];
    } 
    
    [pool release];
    
}

-(void)DisplayWaiting:(BOOL)display
{
    approval.hidden = !display;
}

-(void)DisplayBlocked{    
    [blockedView setHidden:NO];
    
}

-(IBAction)hideBlockedWindow:(id)sender{
    [blockedView setHidden:YES];
    [self cancelDownload];
    
}

-(void)BarUpdate:(float)Progress
{
	int progInt = Progress * 100;
	progressBar.progress = Progress;
	greeting.text = [NSString stringWithFormat:@"Your presentation is loading...%d%%", progInt];
	
	if(progInt == 100)
    {
		[_delegate InitialSlideSession];
    }
}

-(IBAction)updatePrefs:(id)sender
{
	/*
     NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
     [prefs setObject:userName.text forKey:@"activeDeckUserName"];
     [prefs setObject:userEmail.text forKey:@"activeDeckUserEmail"];
     [userName resignFirstResponder];
     greeting.text = @"Application Preference Saves!";
	 */
}

-(IBAction)showInfo:(id)sender
{
	NSLog(@"Show the About Window");
	AboutViewController *info = [[AboutViewController alloc] init];
	info.modalPresentationStyle = UIModalPresentationFormSheet;
	info.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
	[self presentModalViewController:info animated:YES];
    
    [info release];
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

-(void)setTheEnvironment:(AD_Environment *)theEnvironment{
    self.environment = theEnvironment;
    Username_Label.text = theEnvironment.simpleUsername;
}

#pragma mark -
#pragma mark Regular iOS View Handling Function

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
    [super viewDidLoad];
    
    //    // check for internet connection
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
    //    
    //    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    //    [internetReachable startNotifier];
    //    
    //    // check if a pathway to a random host exists
    //    hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
    //    [hostReachable startNotifier];
    
    
    [presentID setDelegate:self];
    loadingView.layer.cornerRadius = 5;
    
    PIDupdater = [AvailablePID alloc];
    [PIDupdater initialize];
    
    [self updatePIDList];
    
    [PIDTable.layer setCornerRadius:5.0];
    [PIDTable.layer setMasksToBounds:YES];
    loginVC = [LoginViewController alloc];
    [loginVC setDelegate:self]; 
    
    environment = [[AD_Environment alloc] init];      
    loginVC.environment = environment;
    
    if (environment.hasLogin) {
        Username_Label.text = environment.simpleUsername;
        Username_Label.hidden = NO;
        loggedInBar.hidden = NO;
        Bt_Logout.hidden = NO;        
    } else {
        Username_Label.hidden = YES;
        loggedInBar.hidden = YES;
        Bt_Logout.hidden = YES;
    }
    
    [self showVersion];
    
    [self BonjourCheck];
    
    avaibleTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(BonjourCheck) userInfo:nil repeats:YES];
    
#ifdef RELEASE
	[self redirectConsoleLogToDocumentFolder];
	[self ScanLogForError];
#endif
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.    
    if(interfaceOrientation == UIDeviceOrientationPortrait) return YES;
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [blockedView release];
    [greeting release];
    [approval release];
    [presentID release];
    [progressBar release];
    [Bt_Logout release];
    [presentName release];
    [PIDTable release];
    [PIDTableCell release];
    [ErrorLogText release];
    [cont_Username release];
    [PIDupdater release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}


@end
